package com.github.thinwonton.excel2sql.model;

import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Data
public class ExcelRow {

    private static Pattern humpPattern = Pattern.compile("[A-Z]");

    @Excel(name = "Field Comment")
    private String fieldComment;

    @Excel(name = "Field Name")
    private String fieldName;

    /**
     * 转换前的字段名，会自动转换成下划线的格式
     */
    @Excel(name = "Raw Field Name")
    private String rawFieldName;

    @Excel(name = "Data Type")
    private String dataType;

    @Excel(name = "Primary Key")
    private String primaryKey;

    @Excel(name = "Index Type")
    private String indexType;

    @Excel(name = "Not Null")
    private String notNull;

    @Excel(name = "Default")
    private String defaultVal;

    public String getFieldName() {
        if (StringUtils.isNotEmpty(rawFieldName)) {
            //先把下划线去除

            return humpToLine2(rawFieldName);
        } else {
            return fieldName;
        }

    }

    /**
     * 驼峰转下划线,效率比上面高
     */
    public static String humpToLine2(final String str) {
        //把下划线去掉
        String original = str.replace("_", "");

        Matcher matcher = humpPattern.matcher(original);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);

        String result = sb.toString();
        if (result.startsWith("_")) {
            return result.substring(1);
        } else {
            return sb.toString();
        }
    }
}
